package com.miyu.client1.dao.book;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.miyu.client1.pojo.book.BookChapter;
import com.miyu.client1.utils.baseDao.BaseDao;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public interface bookChapterDao extends  BaseDao<BookChapter,String>{

    default void saveBookChapter(JSONArray jo){
        //获取当前书籍信息
        List<BookChapter> info = jo.toJavaList(BookChapter.class);
        List<BookChapter> bc = new ArrayList<>();

       if(info.size()>0){
           BookChapter bct = info.get(0);
           String bookId = bct.getBookId();
           //获取章节详细信息 匹配如果有相同则不保存 否者保存数据
           JSONObject cht = getBookInfo(bookId);
           if (cht.isEmpty()){
               saveBatch(info);
           }else {
               for (int i = 0; i < info.size(); i++) {
                   BookChapter bookChapter = info.get(i);
                   if (cht.containsKey(bookChapter.getChapterName()))
                       continue;
                   else {
                       bc.add(bookChapter);
                   }

               }
               //数据保存
               saveBatch(bc);
           }
        }

    }

    public default  JSONObject getBookInfo(String bookId){
        JSONObject rs = new JSONObject();
        StringBuffer sql = new StringBuffer();
        sql.append(" from BookChapter where bookId = '").append(bookId).append("' order by chapterNum ");
        List<BookChapter> bookChapters = this.queryListByHql(sql.toString());
        for (BookChapter bookChapter:bookChapters) {
            rs.put(bookChapter.getChapterName(),bookChapter);

        }
        return  rs;
    }
    /**
     * 判断当前网站是否完全
     * @param str
     * @return
     */
    public default JSONObject querybookSource(String str){
        JSONObject ds = new JSONObject();
        StringBuffer sql = new StringBuffer();
        sql.append(" select book_id,book_rule_source,book_name,CAST(substring(book_source, 23) as SIGNED)  ts from book_list_info  ");
        sql.append(" where book_rule_source='").append(str).append("'");
        sql.append(" order by ts");
        List<Map<String, Object>> mpList = this.queryListBySql(sql.toString());
        if(mpList.size()>0){
            for (Map<String,Object> map: mpList
            ) {
                ds.put(map.get("ts").toString(),map);
            }
        }
        return ds;
    }


    public  default void saveOrUpdateBatcn(List<String> sqlList) {
        this.doExecuteBatch(sqlList);
    }


}
